import sys
import time
import string
from PyQt4 import QtGui, QtCore

class TimeConvertor(QtGui.QMainWindow):
    """a simple time convertor between secs and time"""
    def __init__(self, parent = None):
        """setup Ui and connect Singal/Slot"""
        QtGui.QMainWindow.__init__(self, parent)
        self.__setupUi()
        self.__connectSingalSlot()

    def __setupUi(self):
        """widgets, layout etc."""
        #window title
        self.setWindowTitle(self.tr("TimeConvertor"))

        #radio buttons
        self.secToStrRadioButton = QtGui.QRadioButton(self.tr("SecsToTime"), self)
        self.secToStrRadioButton.setChecked(True)
        self.strToSecRadioButton = QtGui.QRadioButton(self.tr("TimeToSecs"), self)
        radioButtonLayout = QtGui.QHBoxLayout()
        radioButtonLayout.addWidget(self.secToStrRadioButton)
        radioButtonLayout.addWidget(self.strToSecRadioButton)
        groupBox = QtGui.QGroupBox(self)
        groupBox.setLayout(radioButtonLayout)
        groupBox.setFlat(True)

        #time widgets
        curDateTime = QtCore.QDateTime.currentDateTime()

        secLabel = QtGui.QLabel(self.tr("SecsSince1Jan1970UTC"), self)
        self.secLineEdit = QtGui.QLineEdit(str(curDateTime.toTime_t()), self)
        self.secLineEdit.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp("^[0-9]+$"), self))

        strLabel = QtGui.QLabel(self.tr("LocalTime"), self)
        self.strDateTimeEdit = QtGui.QDateTimeEdit(curDateTime, self)
        self.strDateTimeEdit.setDisabled(True)
        self.strDateTimeEdit.setCalendarPopup(True)
        self.strDateTimeEdit.setDisplayFormat("yyyy-MM-dd hh:mm:ss")
        self.strDateTimeEdit.setDateRange(QtCore.QDate(1970,1,1), QtCore.QDate(2106,2,7))

        self.utcDateTimeLabel = QtGui.QLabel("(UTC: " + curDateTime.toUTC().toString("yyyy-MM-dd hh:mm:s") + ")", self)
        palette = self.utcDateTimeLabel.palette()
        palette.setColor(QtGui.QPalette.WindowText,QtGui.QColor(0,0,255))
        self.utcDateTimeLabel.setPalette(palette)

        timeLayout = QtGui.QGridLayout()
        timeLayout.addWidget(secLabel, 0, 0)
        timeLayout.addWidget(self.secLineEdit, 0, 1)
        timeLayout.addWidget(strLabel, 1, 0)
        timeLayout.addWidget(self.strDateTimeEdit, 1, 1)
        timeLayout.addWidget(self.utcDateTimeLabel, 2, 1)

        #main buttons
        self.convertButton = QtGui.QPushButton(self.tr("Convert"), self)
        self.quitButton = QtGui.QPushButton(self.tr("Quit"), self)
        buttonLayout = QtGui.QHBoxLayout()
        buttonLayout.addWidget(self.convertButton)
        buttonLayout.addWidget(self.quitButton)

        #main layout
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(groupBox)
        mainLayout.addLayout(timeLayout)
        mainLayout.addLayout(buttonLayout)

        #central widget
        centralWidget = QtGui.QWidget()
        centralWidget.setLayout(mainLayout)
        self.setCentralWidget(centralWidget)

    def __connectSingalSlot(self):
        QtCore.QObject.connect(self.quitButton, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("close()"))
        QtCore.QObject.connect(self.secToStrRadioButton, QtCore.SIGNAL("toggled(bool)"), self.__changeTimeEditStatus);
        QtCore.QObject.connect(self.convertButton, QtCore.SIGNAL("clicked()"), self.__convertTime)
        QtCore.QObject.connect(self.strDateTimeEdit, QtCore.SIGNAL("dateTimeChanged(const QDateTime&)"), self.__setUTCDateTimeLabel)

    def __changeTimeEditStatus(self, checkState):
        """enable/disable time widgets by the states of radio buttons"""
        self.secLineEdit.setEnabled(checkState)
        self.strDateTimeEdit.setEnabled(not checkState)

    def __convertTime(self):
        """convert time between secs since 1Jan1970UTC and string expression"""
        if self.secToStrRadioButton.isChecked():
            (secs, ok) = self.secLineEdit.text().toULong()
            if ok:
                self.strDateTimeEdit.setDateTime(QtCore.QDateTime.fromTime_t(secs))
            else:
                QtGui.QMessageBox.critical(self, self.tr("ERROR"), self.tr("Convert failed. Please check seconds number <= 2^32 (4294967295)!"))
        else:
            curDateTime = self.strDateTimeEdit.dateTime()
            if curDateTime.secsTo(QtCore.QDateTime.fromTime_t(0)) > 0:
                QtGui.QMessageBox.critical(self, self.tr("ERROR"), self.tr("Convert failed. Please check date and time!"))
            else:
                secs = curDateTime.toTime_t()
                self.secLineEdit.setText(str(secs))

    def __setUTCDateTimeLabel(self, dateTime):
        self.utcDateTimeLabel.setText("(UTC: " + dateTime.toUTC().toString("yyyy-MM-dd hh:mm:ss") + ")")

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv) 
    #translator
    translator = QtCore.QTranslator()
    translator.load("TimeConvertor_" + QtCore.QLocale.system().name(), ".")
    app.installTranslator(translator)
    #show window
    w = TimeConvertor()
    w.show() 
    sys.exit(app.exec_())
